import React, { useState, useEffect } from 'react';
import { toast } from '@/lib/toast-with-audio';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { motion } from 'framer-motion';
import Drawer from "@/components/Drawer";
import { useTheme } from '@/hooks/useTheme';
import { productApi } from '@/store/product';
import { Product, GetProductsParams } from '@/types/product';
import { productProgressData, productRequirementsData } from '@/data/productData';

// 图表数据
const progressChartData = [
  { name: '权限系统', 已完成: 75, 未完成: 25 },
  { name: '用户中心', 已完成: 90, 未完成: 10 },
  { name: '支付平台', 已完成: 30, 未完成: 70 },
  { name: '数据分析', 已完成: 100, 未完成: 0 },
  { name: '消息系统', 已完成: 60, 未完成: 40 },
  { name: 'API网关', 已完成: 100, 未完成: 0 },
];

// 需求数概览数据
const requirementsChartData = [
  { name: '权限系统', 总需求: 45, 已完成: 32, 进行中: 8, 待处理: 5 },
  { name: '用户中心', 总需求: 38, 已完成: 28, 进行中: 6, 待处理: 4 },
  { name: '支付平台', 总需求: 52, 已完成: 15, 进行中: 12, 待处理: 25 },
  { name: '数据分析', 总需求: 28, 已完成: 28, 进行中: 0, 待处理: 0 },
  { name: '消息系统', 总需求: 36, 已完成: 20, 进行中: 10, 待处理: 6 },
  { name: 'API网关', 总需求: 22, 已完成: 22, 进行中: 0, 待处理: 0 },
];

// 状态徽章组件
const StatusBadge: React.FC<{ status: string }> = ({ status }) => {
  let className = '';
  
  switch (status) {
    case '已上线':
      className = 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300';
      break;
    case '开发中':
      className = 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300';
      break;
    case '测试中':
      className = 'bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300';
      break;
    case '规划中':
      className = 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
      break;
    default:
      className = 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
  }
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {status}
    </span>
  );
};

// 进度条组件
const ProgressBar: React.FC<{ progress: number }> = ({ progress }) => {
  return (
    <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5">
      <div 
        className="bg-blue-600 dark:bg-blue-500 h-2.5 rounded-full transition-all duration-500 ease-out" 
        style={{ width: `${progress}%` }}
      ></div>
    </div>
  );
};

export default function Products() {
  const { isDark } = useTheme();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    category: '',
    status: '规划中' as '规划中' | '开发中' | '测试中' | '已上线',
    progress: 0,
    manager: '',
    description: '',
    startDate: '',
    endDate: ''
  });
  
  // 加载产品数据
  useEffect(() => {
    loadProducts();
  }, []);
  
  const loadProducts = async () => {
    setLoading(true);
    try {
      const params: GetProductsParams = {};
      if (searchTerm) params.search = searchTerm;
      if (statusFilter !== 'all') params.status = statusFilter;
      if (categoryFilter !== 'all') params.category = categoryFilter;
      
      const response = await productApi.getProducts(params);
      setProducts(response.data);
    } catch (error) {
      toast('加载产品数据失败');
      console.error('加载产品数据失败:', error);
    } finally {
      setLoading(false);
    }
  };
  
  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      loadProducts();
    }
  };
  
  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    // 防抖搜索
    clearTimeout((window as any).searchTimeout);
    (window as any).searchTimeout = setTimeout(() => {
      loadProducts();
    }, 500);
  };
  
  const handleStatusFilterChange = (value: string) => {
    setStatusFilter(value);
    loadProducts();
  };
  
  const handleCategoryFilterChange = (value: string) => {
    setCategoryFilter(value);
    loadProducts();
  };
  
  const handleCreateProduct = () => {
    setIsDrawerOpen(true);
  };
  
  const handleCloseDrawer = () => {
    setIsDrawerOpen(false);
  };
  
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ 
      ...prev, 
      [name]: name === 'progress' ? parseInt(value) || 0 : value 
    }));
  };
  
  const handleSubmit = async () => {
    // 表单验证
    if (!formData.name) {
      toast('请输入产品名称');
      return;
    }
    
    if (!formData.code) {
      toast('请输入产品代码');
      return;
    }
    
    try {
      await productApi.createProduct(formData);
      toast('产品已创建');
      setIsDrawerOpen(false);
      loadProducts(); // 重新加载产品列表
      
      // 重置表单
      setFormData({
        name: '',
        code: '',
        category: '',
        status: '规划中',
        progress: 0,
        manager: '',
        description: '',
        startDate: '',
        endDate: ''
      });
    } catch (error) {
      toast('创建产品失败');
      console.error('创建产品失败:', error);
    }
  };
  
  return (
    <div>
      <div className="mb6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
        <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">产品管理</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">管理所有产品线的信息与状态</p>
        </motion.div>
      </div>
      
      {/* 工具栏 */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <input 
              type="text" 
              placeholder="搜索产品..." 
              className="py-2 pl-10 pr-4 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              value={searchTerm}
              onChange={(e) => handleSearchChange(e.target.value)}
              onKeyDown={handleSearch}
            />
            <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-500"></i>
          </div>
          
          <select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={statusFilter}
            onChange={(e) => handleStatusFilterChange(e.target.value)}
          >
            <option value="all">全部状态</option>
            <option value="规划中">规划中</option>
            <option value="开发中">开发中</option>
            <option value="测试中">测试中</option>
            <option value="已上线">已上线</option>
          </select>
          
          <select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={categoryFilter}
            onChange={(e) => handleCategoryFilterChange(e.target.value)}
          >
            <option value="all">全部分类</option>
            <option value="基础设施">基础设施</option>
            <option value="核心服务">核心服务</option>
            <option value="数据服务">数据服务</option>
            <option value="应用服务">应用服务</option>
            <option value="其他">其他</option>
          </select>
        </div>
        
        <button 
          className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
          onClick={handleCreateProduct}
        >
          <i className="fa-solid fa-plus mr-2"></i>
          新建产品
        </button>
      </div>
      
      {/* 产品概览图表 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        {/* 产品进度概览 */}
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6"
        >
          <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-4">产品进度概览</h2>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={progressChartData}
                margin={{ top: 20, right: 30, left: 20, bottom: 40 }}
              >
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 12 }} angle={-45} textAnchor="end" height={60} />
                <YAxis tickFormatter={(value) => `${value}%`} />
                <Tooltip formatter={(value) => [`${value}%`, '']} />
                <Legend />
                <Bar dataKey="已完成" stackId="a" fill="#3b82f6" radius={[4, 4, 0, 0]} barSize={30} />
                <Bar dataKey="未完成" stackId="a" fill="#e5e7eb" radius={[0, 0, 4, 4]} barSize={30} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </motion.div>

        {/* 需求数概览 */}
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.1 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6"
        >
          <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-4">需求数概览</h2>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={requirementsChartData}
                margin={{ top: 20, right: 30, left: 20, bottom: 40 }}
              >
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 12 }} angle={-45} textAnchor="end" height={60} />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="已完成" fill="#10b981" radius={[4, 4, 0, 0]} barSize={20} />
                <Bar dataKey="进行中" fill="#f59e0b" radius={[0, 0, 0, 0]} barSize={20} />
                <Bar dataKey="待处理" fill="#ef4444" radius={[0, 0, 4, 4]} barSize={20} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </motion.div>
      </div>
      
      {/* 产品列表 */}
      <motion.div 
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.3, delay: 0.2 }}
        className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden"
      >
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead className="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">产品名称</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">分类</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">负责人</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">进度</th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">创建日期</th>
                <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {loading ? (
                <tr>
                  <td colSpan={7} className="px-6 py-8 text-center">
                    <div className="flex justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    </div>
                    <p className="mt-2 text-gray-500 dark:text-gray-400">加载中...</p>
                  </td>
                </tr>
              ) : products.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
                    暂无产品数据
                  </td>
                </tr>
              ) : (
                products.map((product) => (
                  <tr key={product.id} className="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="font-medium text-gray-900 dark:text-gray-100">{product.name}</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">ID: {product.code}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded-full text-gray-800 dark:text-gray-200">{product.category}</span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">{product.manager}</td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <StatusBadge status={product.status} />
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <ProgressBar progress={product.progress} />
                        <span className="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">{product.progress}%</span>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">{product.createdAt}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 mr-4">
                        <i className="fa-solid fa-pen-to-square mr-1"></i>编辑
                      </button>
                      <button className="text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300">
                        <i className="fa-solid fa-trash mr-1"></i>删除
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        
        {/* 分页 */}
        <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <div className="text-sm text-gray-500 dark:text-gray-400">显示 1 至 {products.length} 条，共 {products.length} 条</div>
          <div className="flex space-x-2">
            <button className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
              <i className="fa-solid fa-chevron-left text-xs"></i>
            </button>
            <button className="px-3 py-1 border border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900 text-blue-600 dark:text-blue-300 rounded-md">1</button>
            <button className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600">2</button>
            <button className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600">3</button>
            <button className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600">
              <i className="fa-solid fa-chevron-right text-xs"></i>
            </button>
          </div>
        </div>
      </motion.div>
      
      {/* 新建产品抽屉 */}
      <Drawer 
        isOpen={isDrawerOpen} 
        onClose={handleCloseDrawer} 
        title="新建产品"
        footer={
          <div className="flex justify-end space-x-3">
            <button 
              className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
              onClick={handleCloseDrawer}
            >
              取消
            </button>
            <button 
              className="px-4 py-2 bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600"
              onClick={handleSubmit}
            >
              保存
            </button>
          </div>
        }
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品名称 <span className="text-red-500">*</span></label>
            <input 
              type="text" 
              name="name" 
              value={formData.name} 
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              placeholder="请输入产品名称"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品代码 <span className="text-red-500">*</span></label>
            <input 
              type="text" 
              name="code" 
              value={formData.code} 
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              placeholder="请输入产品代码（如：PROD-001）"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品分类</label>
            <select 
              name="category" 
              value={formData.category} 
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            >
              <option value="">请选择分类</option>
              <option value="基础设施">基础设施</option>
              <option value="核心服务">核心服务</option>
              <option value="数据服务">数据服务</option>
              <option value="应用服务">应用服务</option>
              <option value="其他">其他</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品状态</label>
            <select 
              name="status" 
              value={formData.status} 
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            >
              <option value="规划中">规划中</option>
              <option value="开发中">开发中</option>
              <option value="测试中">测试中</option>
              <option value="已上线">已上线</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">进度 (%)</label>
            <input 
              type="number" 
              name="progress" 
              value={formData.progress} 
              onChange={handleInputChange}
              min="0"
              max="100"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              placeholder="请输入进度（0-100）"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品经理</label>
            <select 
              name="manager" 
              value={formData.manager} 
              onChange={handleInputChange}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            >
              <option value="">请选择产品经理</option>
              <option value="张产品">张产品</option>
              <option value="李产品">李产品</option>
              <option value="王产品">王产品</option>
              <option value="赵产品">赵产品</option>
              <option value="钱产品">钱产品</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品描述</label>
            <textarea 
              name="description" 
              value={formData.description} 
              onChange={handleInputChange}
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              placeholder="请输入产品描述"
            ></textarea>
          </div>
          
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">开始日期</label>
              <input 
                type="date" 
                name="startDate" 
                value={formData.startDate} 
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">预计上线日期</label>
              <input 
                type="date" 
                name="endDate" 
                value={formData.endDate} 
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              />
            </div>
          </div>
        </div>
      </Drawer>
    </div>
  );
}